<template>
  <view class="appointment-container">
    <view class="header">
      <view class="title">预约拜访</view>
      <view class="subtitle">填写信息预约校园拜访</view>
    </view>
    
    <view class="form-card">
      <view class="form-item">
        <text class="label">拜访目的</text>
        <input 
          class="input" 
          placeholder="请输入拜访目的" 
          v-model="formData.purpose"
        />
      </view>
      
      <view class="form-item">
        <text class="label">拜访地点</text>
        <picker 
          class="picker" 
          mode="selector" 
          :range="locationOptions" 
          @change="onLocationChange"
        >
          <view class="picker-text">{{ formData.location || '请选择拜访地点' }}</view>
        </picker>
      </view>
      
      <view class="form-item">
        <text class="label">拜访日期</text>
        <picker 
          class="picker" 
          mode="date" 
          :start="minDate" 
          :end="maxDate" 
          @change="onDateChange"
        >
          <view class="picker-text">{{ formData.date || '请选择拜访日期' }}</view>
        </picker>
      </view>
      
      <view class="form-item">
        <text class="label">拜访时间</text>
        <picker 
          class="picker" 
          mode="time" 
          :start="'08:00'" 
          :end="'18:00'" 
          @change="onTimeChange"
        >
          <view class="picker-text">{{ formData.time || '请选择拜访时间' }}</view>
        </picker>
      </view>
      
      <view class="form-item">
        <text class="label">联系电话</text>
        <input 
          class="input" 
          type="number" 
          maxlength="11" 
          placeholder="请输入联系电话" 
          v-model="formData.phone"
        />
      </view>
      
      <view class="form-item textarea-item">
        <text class="label">备注信息</text>
        <textarea 
          class="textarea" 
          placeholder="请输入备注信息（选填）" 
          v-model="formData.remark"
        />
      </view>
    </view>
    
    <view class="appointment-list" v-if="appointmentList.length > 0">
      <view class="list-header">
        <text class="list-title">我的预约</text>
      </view>
      
      <view 
        class="appointment-item" 
        v-for="(item, index) in appointmentList" 
        :key="index"
      >
        <view class="item-header">
          <text class="item-purpose">{{ item.purpose }}</text>
          <text class="item-status" :class="statusClassMap[item.status]">{{ getStatusText(item.status) }}</text>
        </view>
        
        <view class="item-content">
          <view class="item-info">
            <text class="info-label">拜访地点：</text>
            <text class="info-value">{{ item.location }}</text>
          </view>
          
          <view class="item-info">
            <text class="info-label">拜访时间：</text>
            <text class="info-value">{{ item.date }} {{ item.time }}</text>
          </view>
          
          <view class="item-info" v-if="item.remark">
            <text class="info-label">备注信息：</text>
            <text class="info-value">{{ item.remark }}</text>
          </view>
        </view>
        
        <view class="item-footer">
          <text class="item-time">提交时间：{{ item.createTime }}</text>
          <button 
            class="cancel-btn" 
            size="mini" 
            v-if="item.status === 0" 
            @click="cancelAppointment(item.id)"
          >取消预约</button>
        </view>
      </view>
    </view>
    
    <view class="submit-btn-wrapper">
      <button class="submit-btn" @click="submitAppointment">提交预约</button>
    </view>
  </view>
</template>

<script>
import request from '@/utils/request.js';
export default {
  data() {
    return {
      formData: {
        purpose: '',
        location: '',
        date: '',
        time: '',
        phone: '',
        remark: ''
      },
      locationOptions: ['行政楼', '教学楼', '图书馆', '实验室', '体育馆', '学生宿舍', '其他'],
      appointmentList: [],
      minDate: this.formatDate(new Date()),
      maxDate: this.formatDate(new Date(new Date().setMonth(new Date().getMonth() + 3))),
      statusClassMap: {
        0: 'status-pending',
        1: 'status-approved',
        2: 'status-rejected',
        3: 'status-canceled',
        4: 'status-completed'
      }
    };
  },
  onLoad() {
    this.getAppointmentList();
  },
  methods: {
    // 获取预约列表
    getAppointmentList() {
      request.get('/appointment/list')
        .then(res => {
          this.appointmentList = res.data || [];
        })
        .catch(err => {
          console.error('获取预约列表失败:', err);
          uni.showToast({
            title: '获取预约列表失败',
            icon: 'none'
          });
        });
    },
    
    // 提交预约
    submitAppointment() {
      // 表单验证
      if (!this.validateForm()) {
        return;
      }
      
      // 显示加载提示
      uni.showLoading({
        title: '提交中...'
      });
      
      // 发送请求
      request.post('/appointment/create', this.formData)
        .then(res => {
          uni.hideLoading();
          uni.showToast({
            title: '预约提交成功',
            icon: 'success'
          });
          
          // 重置表单
          this.resetForm();
          
          // 刷新预约列表
          this.getAppointmentList();
        })
        .catch(err => {
          uni.hideLoading();
          console.error('预约提交失败:', err);
          uni.showToast({
            title: '预约提交失败',
            icon: 'none'
          });
        });
    },
    
    // 取消预约
    cancelAppointment(id) {
      uni.showModal({
        title: '提示',
        content: '确定要取消该预约吗？',
        success: (res) => {
          if (res.confirm) {
            request.post(`/appointment/cancel?id=${id}`)
              .then(res => {
                uni.showToast({
                  title: '取消成功',
                  icon: 'success'
                });
                
                // 刷新预约列表
                this.getAppointmentList();
              })
              .catch(err => {
                console.error('取消预约失败:', err);
                uni.showToast({
                  title: '取消预约失败',
                  icon: 'none'
                });
              });
          }
        }
      });
    },
    
    // 表单验证
    validateForm() {
      if (!this.formData.purpose) {
        uni.showToast({
          title: '请输入拜访目的',
          icon: 'none'
        });
        return false;
      }
      
      if (!this.formData.location) {
        uni.showToast({
          title: '请选择拜访地点',
          icon: 'none'
        });
        return false;
      }
      
      if (!this.formData.date) {
        uni.showToast({
          title: '请选择拜访日期',
          icon: 'none'
        });
        return false;
      }
      
      if (!this.formData.time) {
        uni.showToast({
          title: '请选择拜访时间',
          icon: 'none'
        });
        return false;
      }
      
      if (!this.formData.phone) {
        uni.showToast({
          title: '请输入联系电话',
          icon: 'none'
        });
        return false;
      }
      
      const phoneReg = /^1[3-9]\d{9}$/;
      if (!phoneReg.test(this.formData.phone)) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        });
        return false;
      }
      
      return true;
    },
    
    // 重置表单
    resetForm() {
      this.formData = {
        purpose: '',
        location: '',
        date: '',
        time: '',
        phone: '',
        remark: ''
      };
    },
    
    // 选择器事件处理
    onLocationChange(e) {
      const index = e.detail.value;
      this.formData.location = this.locationOptions[index];
    },
    
    onDateChange(e) {
      this.formData.date = e.detail.value;
    },
    
    onTimeChange(e) {
      this.formData.time = e.detail.value;
    },
    
    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: '待审核',
        1: '已通过',
        2: '已拒绝',
        3: '已取消',
        4: '已完成'
      };
      return statusMap[status] || '未知状态';
    }
  }
};
</script>

<style lang="scss" scoped>
.appointment-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-bottom: 120rpx;
}

.header {
  background: linear-gradient(to right, #4f99ff, #6ba6ff);
  padding: 40rpx 30rpx;
  color: #fff;
  border-bottom-left-radius: 20rpx;
  border-bottom-right-radius: 20rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.subtitle {
  font-size: 24rpx;
  opacity: 0.8;
}

.form-card {
  margin: 30rpx;
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.form-item {
  margin-bottom: 30rpx;
}

.label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 15rpx;
  font-weight: 500;
}

.input, .picker {
  width: 100%;
  height: 80rpx;
  border: 1px solid #e8e8e8;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  background-color: #f9f9f9;
}

.picker {
  display: flex;
  align-items: center;
}

.picker-text {
  color: #333;
}

.textarea-item {
  margin-bottom: 0;
}

.textarea {
  width: 100%;
  height: 160rpx;
  border: 1px solid #e8e8e8;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 28rpx;
  background-color: #f9f9f9;
}

.appointment-list {
  margin: 30rpx;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.list-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.appointment-item {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 15rpx;
  border-bottom: 1px solid #f0f0f0;
}

.item-purpose {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}

.item-status {
  font-size: 24rpx;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
}

.status-pending {
  background-color: #e6f7ff;
  color: #1890ff;
}

.status-approved {
  background-color: #f6ffed;
  color: #52c41a;
}

.status-rejected {
  background-color: #fff2f0;
  color: #ff4d4f;
}

.status-canceled {
  background-color: #f5f5f5;
  color: #999;
}

.status-completed {
  background-color: #f0f5ff;
  color: #597ef7;
}

.item-content {
  padding: 15rpx 0;
}

.item-info {
  display: flex;
  margin-bottom: 10rpx;
  font-size: 26rpx;
}

.info-label {
  color: #666;
  width: 160rpx;
  flex-shrink: 0;
}

.info-value {
  color: #333;
  flex: 1;
}

.item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 15rpx;
  border-top: 1px solid #f0f0f0;
}

.item-time {
  font-size: 24rpx;
  color: #999;
}

.cancel-btn {
  font-size: 24rpx;
  color: #ff4d4f;
  background-color: #fff2f0;
  border: 1px solid #ffccc7;
}

.submit-btn-wrapper {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 30rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.submit-btn {
  background: linear-gradient(to right, #4f99ff, #6ba6ff);
  color: #fff;
  border-radius: 44rpx;
  font-size: 32rpx;
  height: 88rpx;
  line-height: 88rpx;
}
</style> 